# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import time

import logging

_logger = logging.getLogger(__name__)


def virtual_ocr_method(fapiao):
    print('virtual_ocr_method', fapiao)
    time.sleep(3)
    result = [{'id': one.id,
               'state': 'done',
               # todo, 其他字段的 模拟值
               } for one in fapiao]
    return result


class FapiaoApiOCR(models.Model):
    _name = "fp.api.ocr"
    _description = "Fapiao Api OCR"
    _order = 'sequence, name'

    name = fields.Char(
        string='Provider name', required=True,
        help="Name of Provider, Baiwang, Aisino, etc")

    code = fields.Char(
        string='Provider Code', required=True,
        help="Code of Provider, Baiwang, Aisino, etc, Unique")

    endpoint = fields.Char(
        string='URL', required=True, help="provider URL")

    sequence = fields.Integer(default=10)

    _sql_constraints = [
        ('code_key', 'UNIQUE (code)',
         'You can not set twe api providers for the same code !')
    ]

    def _request_methods(self):
        # to override.
        # update other  _request_methods
        return {'virtual': virtual_ocr_method}

    def _request_method_get(self):
        methods = self._request_methods()
        return methods.get(self.code)


class ApiOcrCompany(models.Model):
    _name = "fp.api.ocr.company"
    _description = "Api OCR Company"

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    name = fields.Char(
        string='Name', related='company_id.name', store=True)

    tin = fields.Char(
        string='TIN', related="company_id.partner_id.vat", store=True)

    # ocr_provider_id
    api_ocr_id = fields.Many2one(
        'fp.api.ocr', string='Api OCR')

    @api.model
    def search_by_company(self, company_id):
        return self.search([('company_id', '=', company_id.id)], limit=1)

    _sql_constraints = [
        ('company_id_key', 'UNIQUE (company_id)',
         'You can not set two times for the same company !')
    ]
